# -*- coding: utf-8 -*-
import os
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template
from google.appengine.ext import db

from emof import core as EMOF
from emof import dumper
from emof import loader

from model import Model

class LoadEnumerationLiteralData(webapp.RequestHandler):
    def get(self):
        m_id = self.request.get("m_id")
        o_id = self.request.get("id")
        model = Model.get(m_id)

        rep = loader.Loader().load(model.model_XMI)
        self.response.headers['Content-Type'] = 'application/xml'
        xml = "<r></r>"

        el = rep.findEnumerationLiteral(o_id)

        template_values = {'id': o_id,
                           'el': el}
        
        path = os.path.join(os.getcwd(), 'xml/EnumerationLiteral.xml')
        xml = template.render(path, template_values)
        self.response.out.write(xml)
                
class SaveEnumerationLiteralData(webapp.RequestHandler):
    def post(self):
        m_id = self.request.get("m_id")
        o_id = self.request.get("id")
        name = self.request.get("name")
        
        model = Model.get(m_id)

        rep = loader.Loader().load(model.model_XMI)
        
        el = rep.findEnumerationLiteral(o_id)
        el.name = name
        model.model_XMI = dumper.Dumper().dump(rep)
        model.put()
        self.response.out.write("OK")
        
class CreateEnumerationLiteralData(webapp.RequestHandler):
    def get(self):
        m_id = self.request.get("m_id")
        
        if self.request.get("p_id") != "":
            e_id = self.request.get("p_id")
        else:
            e_id = '-1'
            
        model = Model.get(m_id)

        rep = loader.Loader().load(model.model_XMI)
        fact = EMOF.Factory(rep)
        el = fact.create_EnumerationLiteral()
        el.name = 'New EnumerationLiteral'
        
        enum = rep.findEnumeration(e_id)
        if enum:
            enum.ownedLiteral.append(el)
            el.enumeration = enum
        model.model_XMI = dumper.Dumper().dump(rep)
        model.put()
        self.response.out.write(el.id + '$$$$' + el.name)